#!usr/bin/env python
# -*- coding: utf-8 -*-
import time
from flask import session

from fx.constants.user import(
    SESSION_USER_ID
)
from fx.data.user import get_admin_user_by_id


def login_user(user, permanent=False):
    if not user:
        return None
    session[SESSION_USER_ID] = user.id
    if permanent:
        session.permanent = True
    return user


def logout_user():
    if SESSION_USER_ID not in session:
        return
    session.pop(SESSION_USER_ID)
    session.clear()


def get_current_admin_user():
    if SESSION_USER_ID in session:
        user = None
        try:
            print session[SESSION_USER_ID]
            user = get_admin_user_by_id(session[SESSION_USER_ID])
        except:
            logout_user()
        if not user:
            return None
        if not user.is_active:
            logout_user()
        else:
            return user
